<template>
    <div class="data">
        <div class="head" :class="{ 'color': type === 'income' }">
            <div class="title">
                <div class="date" @click="changeTime">{{ currentDate[0] }}年{{ currentDate[1] }}月 <van-icon
                        name="calendar-o" /></div>
                <div class="type">
                    <span @click="chooseType('expense')" :class="{ 'active': type === 'expense' }">支出</span>
                    <span @click="chooseType('income')" :class="{ 'active2': type === 'income' }">入账</span>
                </div>
            </div>
            <div class="total">
                <p class="title">共支出</p>
                <p class="num">￥{{ type === 'expense' ? state.totalExpense : state.totalIncome }}</p>
            </div>
        </div>
        <div class="content">
            <div class="structure">
                <p class="title">{{ type === 'expense' ? '支出构成' : '收入构成' }}</p>
                <div class="echarts" ref="echartsRef"></div>
            </div>
            <ul class="list" v-if="type === 'expense'">
                <li class="progress" v-for="item in state.expenseList">
                    <div>
                        <i class="iconfont" :class="icons[item.type_name]"></i>
                        <span>{{ item.type_name }}</span>
                    </div>
                    <van-progress color="#37a762" :percentage="(item.number / state.totalExpense) * 100"
                        :show-pivot="false" class="progress-item" stroke-width="6px" track-color='#fff' />
                    <span>￥{{ item.number.toFixed(2) }}</span>
                </li>
            </ul>
            <ul class="list" v-else>
                <li class="progress" v-for="item in state.incomeList">
                    <div>
                        <i class="iconfont" :class="[icons[item.type_name], { 'color': type === 'income' }]"></i>
                        <span>{{ item.type_name }}</span>
                    </div>
                    <van-progress color="#DEAE2E" :percentage="(item.number / state.totalIncome) * 100"
                        :show-pivot="false" class="progress-item" stroke-width="6px" track-color='#fff' />
                    <span>￥{{ item.number.toFixed(2) }}</span>
                </li>
            </ul>
        </div>
    </div>
    <PopTime @selectDate="selectDate" ref="PopTimeRef"></PopTime>
</template>

<script setup>
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { onMounted, ref, reactive } from 'vue';
import axios from '@/api/index.js'
import formatteDate from '@/utils/date.js'
import PopTime from '@/components/PopTime.vue'
import icons from '@/utils/icons.js'

echarts.use([
    PieChart,
    CanvasRenderer,
    LabelLayout
]);

const echartsRef = ref(null)
const state = reactive({
    totalExpense: 0,
    totalIncome: 0,
    expenseList: [],
    incomeList: []
})
const PopTimeRef = ref(null)
const currentDate = ref(formatteDate(new Date()).slice(0, -1))
const type = ref('expense')

onMounted(() => {
    // 获取数据
    getData()
    // 加载图表

})

const getData = async () => {
    const res = await axios.get(`/api/bill/data?date=${currentDate.value.join('-')}`)
    // console.log(res);

    state.totalExpense = res.data.total_expense;
    state.totalIncome = res.data.total_income;
    state.expenseList = res.data.total_data.filter(item => item.pay_type === 1)
    state.incomeList = res.data.total_data.filter(item => item.pay_type === 2)

    console.log(state.expenseList);
    console.log(state.incomeList);

    const data = []

    if (type.value === 'expense') {
        state.expenseList.forEach(item => {
            data.push({
                value: item.number,
                name: item.type_name,
                payType: item.pay_type
            })
        })
        data.sort((a, b) => {
            return b.value - a.value
        })
        // console.log(data);
        loadPie(data)
    } else {
        state.incomeList.forEach(item => {
            data.push({
                value: item.number,
                name: item.type_name,
                payType: item.pay_type
            })
        })
        data.sort((a, b) => {
            return b.value - a.value
        })
        console.log(data);
        // console.log(1);

        loadPie(data)
    }
}

const loadPie = (data) => {
    const myChart = echarts.init(echartsRef.value);
    const option = {
        series: [
            {
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 4,
                    borderColor: '#fff',
                    borderWidth: 2,
                    color: (obj) => {
                        let len = data.length
                        if (obj.data.payType === 1) {
                            return `rgba(54,169,98,${(len + 3 - obj.dataIndex + 3) / (len + 3).toFixed(1)})`
                        } else {
                            return `rgba(222, 174, 46,${(len + 3 - obj.dataIndex + 3) / (len + 3).toFixed(1)})`
                        }
                    }
                },
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}: {d}%'
                },
                labelLine: {
                    show: true,
                    lineStyle: {
                        color: "#666"
                    }
                },
                data: data || [
                    { value: 1048, name: 'Search Engine' },
                    { value: 735, name: 'Direct' },
                    { value: 580, name: 'Email' },
                    { value: 484, name: 'Union Ads' },
                    { value: 300, name: 'Video Ads' }
                ]
            }
        ]
    };
    myChart.setOption(option);
}

const changeTime = () => {
    PopTimeRef.value.show = true;
}

const selectDate = (type) => {
    // console.log(type);
    currentDate.value = type
    getData()
}

const chooseType = (item) => {
    type.value = item
    getData()
}
</script>

<style lang="less" scoped>
.data {
    overflow: scroll;
    box-sizing: border-box;
    height: calc(100vh - 50px);

    .head {
        padding: 50px 20px;
        background-color: #37a762;
        color: #fff;
        font-size: 16px;
        font-weight: 300;

        .title {
            display: flex;
            justify-content: space-between;

            .type {
                span {
                    margin-left: 10px;
                }

                span.active {
                    padding: 5px 10px;
                    border-radius: 5px;
                    background-color: rgb(69, 178, 113);
                }

                span.active2 {
                    padding: 5px 10px;
                    border-radius: 5px;
                    background-color: #E2B639;
                }
            }

        }

        .total {
            margin-top: 30px;

            .title {
                font-weight: 100;
            }

            .num {
                font-size: 30px;
                font-weight: 500;
                margin-top: 20px;
            }
        }
    }

    .color {
        background-color: #DEAE2E !important;
    }

    .content {
        padding: 30px 20px;


        .structure {
            .title {
                font-size: 16px;
            }

            .echarts {
                width: 100%;
                height: 200px;
                margin-top: 20px;
            }
        }

        .list {
            margin-top: 20px;

            .progress {
                display: flex;
                align-items: center;
                font-size: 14px;
                margin-bottom: 20px;

                div {
                    display: flex;
                    flex: 3;
                    align-items: center;

                    .iconfont {
                        margin-right: 8px;
                        display: inline-block;
                        width: 25px;
                        height: 25px;
                        line-height: 25px;
                        border-radius: 50%;
                        text-align: center;
                        background-color: #37a762;
                        color: #fff;
                    }
                }

                :deep(.progress-item) {
                    flex: 4;
                    margin-right: 10px;
                }

                span {
                    flex: 1;
                }
            }
        }
    }
}
</style>